package com.zzy.face.controller;

import com.zzy.face.dao.ImgFaceDao;
import com.zzy.face.dto.PwdChangeDto;
import com.zzy.face.dto.RegisterDto;
import com.zzy.face.dto.TeacherList;
import com.zzy.face.model.*;
import com.zzy.face.service.impl.*;
import com.zzy.face.utils.*;
import com.zzy.face.utils.jwt.Jwt;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 朱泽玉
 * @Create 2022/1/29 11:11
 * @Description
 * @Modified By:
 */
@RestController
@Api(tags = "账户接口")
public class AccountController {
    @Value("${img.location:''}")
    private String location;
    final AccountServiceImpl accountService;
    final StudentServiceImpl studentService;
    final TeacherServiceImpl teacherService;
    final AdminServiceImpl adminService;
    final CollegeServiceImpl collegeService;
    final Jwt jwt;
    final ImgFaceDao imgFaceDao;
    public AccountController(AccountServiceImpl accountService, StudentServiceImpl studentService, TeacherServiceImpl teacherService, AdminServiceImpl adminService, CollegeServiceImpl collegeService, Jwt jwt, ImgFaceDao imgFaceDao) {
        this.accountService = accountService;
        this.studentService = studentService;
        this.teacherService = teacherService;
        this.adminService = adminService;
        this.collegeService = collegeService;
        this.jwt = jwt;
        this.imgFaceDao = imgFaceDao;
    }

    @RequestMapping(value="/register",method = RequestMethod.POST)
    @ApiOperation(value = "注册", notes = "注册")
    public Result register(@RequestBody RegisterDto form){
        boolean isMobile = PatternUtils.isMobile(form.getMobile());
        boolean isPwd = PatternUtils.isPassword(form.getPassword());
        if (!(isPwd&&isMobile)){
            return new Result(ResultCode.FAIL,"信息不符合规范");
        }
        if (accountService.findByMobile(form.getMobile())!=null){
            return new Result(ResultCode.FAIL,"手机号码已被注册");
        }
        int identity = form.getIdentity();
        Account account = new Account();
        Long uid = SnowflakeIdWorker.getUUID();
        account.setUid(uid);
        account.setMobile(form.getMobile());
        account.setDate_time(PatternUtils.GetTime());
        account.setIdentity(identity);
        account.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        account.setIdNumber(form.getIdNumber());
        account.setName(form.getName());
        account.setSex(form.getSex());
        account.setCollege(form.getCollege());
        account.setState(0);
        try{
            String birthday = PatternUtils.isIDCardNumGetBirth(form.getIdNumber());
            if (birthday==null){
                return new Result(ResultCode.FAIL,"身份证号不符合规范");
            }
            account.setBirthday(PatternUtils.isIDCardNumGetBirth(form.getIdNumber()));
        }catch (Exception e){
            return new Result(ResultCode.FAIL,"身份证号不符合规范");
        }
        if (identity == 1){
            Teacher teacher = new Teacher();
            teacher.setAccount(account);
            teacher.setUid(uid);
            account.setTeacher(teacher);
            teacherService.save(teacher);
        }else if(identity == 0){
            Student student = new Student();
            student.setAccount(account);
            student.setUid(uid);
            student.setMajor(form.getMajor());
            System.out.println(form.getUClass());
            student.setUClass(form.getUClass());
            student.setTeacherId(Long.valueOf(form.getTeacherId()));
            account.setStudent(student);
            studentService.save(student);
        }else if(identity == 2){
            Admin admin = new Admin();
            admin.setAccount(account);
            admin.setUid(uid);
            account.setAdmin(admin);
            adminService.save(admin);
        }
        accountService.save(account);
        return new Result(ResultCode.SUCCESS,account);
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ApiOperation(value = "登录", notes = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "账号", required = true, example = "admin"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, example = "123456")
    })
    public Result login(@RequestParam("mobile")String mobile,
                        @RequestParam("password") String password){
        try {
            Account account = accountService.findByMobile(mobile);
            //密码错误
            if (account == null || !DigestUtils.sha256Hex(password).equals(account.getPassword())) {
                return new Result(ResultCode.FAIL, "用户名不存在或密码错误");
            }
            if (account.getState() != 2) {
                return new Result(ResultCode.UN_AUTHORISE, "冻结账号",account.getState());
            }
            //密码正确
            //赋值token数据
            Map<String, Object> map = new HashMap<>();
            map.put("username", mobile);
            map.put("password", password);
            map.put("identity", account.getIdentity());
            //创建token对象
            String token = jwt.create(Long.toString(account.getUid()), map);
            return new Result(ResultCode.SUCCESS, token, account.getIdentity());
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }

    @RequestMapping(value = "/identity", method = RequestMethod.GET)
    @ApiOperation(value = "获取身份", notes = "获取身份")
    public Result identity(HttpServletRequest request){
        try {
            Claims token = jwt.token(request);
            return new Result(ResultCode.SUCCESS, token.get("identity"));
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }

    @RequestMapping(value = "/pwd", method = RequestMethod.PUT)
    @ApiOperation(value = "修改密码", notes = "修改密码(管理员可直接修改学生+老师，老师可直接修改学生，除此之外都要验证密码适配后修改)")
    public Result changePwd(HttpServletRequest request,@RequestBody PwdChangeDto form){
        int identity = Integer.parseInt(jwt.token(request).get("identity").toString());
        Account account = accountService.findByMobile(form.getMobile());
        if (!(identity>accountService.findByMobile(form.getMobile()).getIdentity())){
            if (account == null || !DigestUtils.sha256Hex(form.getPassword()).equals(account.getPassword())) {
                return new Result(ResultCode.FAIL, "原始密码错误");
            }
        }
        account.setPassword(DigestUtils.sha256Hex(form.getNewPwd()));
        accountService.save(account);
        return new Result(ResultCode.SUCCESS);
    }


    @RequestMapping(value = "/upload/{mobile}", method = RequestMethod.POST)
    @ApiOperation(value = "上传照片", notes = "监测header admin")
    public Result upload(MultipartFile file, HttpServletRequest request, @PathVariable("mobile") String mobile) throws IOException {
        try {
//            Account account = accountService.findByMobile(mobile);
            /***********文件上传操作************/
            //1、获取文件的内容
//        InputStream is = file.getInputStream();
//        inputStream.close();
            Long uid = jwt.getId(request);
            //2、以用户账户id为文件夹
            String fileName = jwt.getId(request).toString();
            // 3、获取文件夹路径
            String firPath = this.location + fileName;
            File fileDir = new File(firPath);
            //4、若文件夹不存在,则创建出文件夹
            if (fileDir.exists()) {
                File[] delFileList = fileDir.listFiles();
                assert delFileList != null;
                for (File curFile : delFileList) {
                    System.out.println(curFile);
                    boolean right = curFile.delete();
                }
            } else {
                fileDir.mkdirs();
            }
            //5、获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //6、根据原始文件名生成文件名
            assert originalFilename != null;
            String uuidFilename = UploadUtils.getUUIDName(originalFilename);
            //7、在文件夹中创建文件
            File newFile = new File(firPath, uuidFilename);
            //8、将文件输出到目标的文件中
            file.transferTo(newFile);

            //将保存的文件路径更新到数据库中
            ImgFace account = imgFaceDao.findByAccount(uid);
            if (account==null){
                ImgFace imgFace = new ImgFace();
                imgFace.setAccount(uid);
                imgFace.setDate_time(PatternUtils.GetTime());
                imgFaceDao.save(imgFace);
            }
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/img/{uid}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation(value = "获取照片", notes = "")
    public byte[] img(HttpServletRequest request,@PathVariable("uid") String uid) throws IOException {
        File fileDir = new File( this.location +'\\'+ uid);
        File[] delFileList = fileDir.listFiles();
        if (fileDir.exists()&&delFileList != null) {
            // 5、获取图片字节
            File img = delFileList[0];
            FileInputStream inputStream = new FileInputStream(img);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            inputStream.close();
            return bytes;
        }else{
            return null;
        }
    }

    @RequestMapping(value = "/teachers", method = RequestMethod.GET)
    @ApiOperation(value = "获取老师列表", notes = "")
    public Result teachers(@RequestParam("college") String college) {
        System.out.println(college);
        List<TeacherList> teacherList = teacherService.findTeacherListByCollege(college);
        return new Result(ResultCode.SUCCESS,teacherList);
    }

    @RequestMapping(value = "/colleges", method = RequestMethod.GET)
    @ApiOperation(value = "获取学院列表", notes = "")
    public Result colleges() {
        List<College> collegeList = collegeService.findAll();
        return new Result(ResultCode.SUCCESS,collegeList);
    }
}
